home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: mxsld2.pd.infn.it!LORETI
- From: loreti@mxsld2.pd.infn.it (Maurizio Loreti)
- Subject: Re: Checking to See if a File Exists
- X-Nntp-Posting-Host: mxsld2.pd.infn.it
- Message-ID: <DM81w4.CB6@news.cern.ch>
- Sender: news@news.cern.ch (USENET News System)
- Reply-To: loreti@mxsld2.pd.infn.it
- Organization: I.N.F.N. Padova - CDF/CMS VAXcluster
- References: <DLtI7G.HpE@midway.uchicago.edu>
- Date: Sat, 3 Feb 1996 22:45:36 GMT
-
- In article <DLtI7G.HpE@midway.uchicago.edu>, jaj3@kimbark.uchicago.edu (josef jurek) writes:
- >
- >How does one check from a C program to see whether a file
- >exists or not?
-
- Apparently, while you read the FAQ list before posting, you missed Q/A
- 19.11.
-
- 19.11: How can I check whether a file exists? I want to warn the user
- if a requested input file is missing.
-
- A: It's surprisingly difficult to make this determination reliably
- and portably. Any test you make can be invalidated if the file
- is created or deleted (i.e. by some other process) between the
- time you make the test and the time you try to open the file.
-
- Three possible test routines are stat(), access(), and fopen().
- (To make an approximate test for file existence with fopen(),
- just open for reading and close immediately.) Of these, only
- fopen() is widely portable, and access(), where it exists, must
- be used carefully if the program uses the Unix set-UID feature.
-
- Rather than trying to predict in advance whether an operation
- such as opening a file will succeed, it's often better to try
- it, check the return value, and complain if it fails.
- (Obviously, this approach won't work if you're trying to avoid
- overwriting an existing file, unless you've got something like
- the O_EXCL file opening option available, which does just what
- you want in this case.)
-
- References: PCS Sec. 12 pp. 189,213; POSIX Sec. 5.3.1,
- Sec. 5.6.2, Sec. 5.6.3.
-
- --
- Maurizio Loreti http://mvxpd5.pd.infn.it/wwwcdf/mlo.html
- Un. of Padova, Dept. of Physics - Padova, Italy loreti@padova.infn.it
-